/**
 * @file markdown
 * @author liyong18@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as marked from 'marked';
import * as highlight from 'highlight.js';

let renderer = new marked.Renderer();
marked.setOptions({
  renderer: renderer,
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false
});
marked.setOptions({
  highlight: function (code) {
    return highlight.highlightAuto(code).value;
  }
});

renderer.link = function (href, title, text) {
  if (this.options.sanitize) {
    try {
      var prot = decodeURIComponent(unescape(href))
        .replace(/[^\w:]/g, '')
        .toLowerCase();
    } catch (e) {
      return '';
    }
    if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
      return '';
    }
  }
  if (href && href[0] === '#') {
    href = '#' + encodeURIComponent(href.substring(1).toLowerCase().replace(/[^\u4e00-\u9fa5_a-zA-Z0-9]+/g, '-'));
  }

  var out = '<a href="' + href + '"';
  if (title) {
    out += ' title="' + title + '"';
  }
  out += '>' + text + '</a>';
  return out;
};


export function compileMarkDownToHtml(content, location) {
  var info = {};
  var toc = {
    label: '内容',
    type: 'toc',
    children: [],
    level: 0
  };
  var stack = [toc];
  const pathname = location.pathname.replace(/^\/(group\/[^\/]+(\/)?)?/, '');
  renderer.heading = function (text, level) {
    var escapedText = encodeURIComponent(text.toLowerCase().replace(/[^\u4e00-\u9fa5_a-zA-Z0-9]+/g, '-'));

    if (level < 5) {
      var menu = {
        label: text,
        url: pathname,
        hash: '#' + escapedText,
        icon: 'fa fa-flag',
        level
      };

      while (stack.length && stack[0].level >= level) {
        stack.shift();
      }

      stack[0].children = stack[0].children || [];
      stack[0].children.push(menu);

      stack.unshift(menu);

    }

    var anchor = '<a class="anchor" name="' + escapedText + '" href="#'+ escapedText +'" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>';

    return '<h' + level + '>' +
      anchor + text +
      '</h' + level +'>';
  };

  const placeholder = {};
  let index = 1;

  content = content.replace(/```(schema|html)(?::(.*?))?\n([\s\S]*?)```/g, function (_, lang, attr, code) {
    if (lang === 'html') {
      placeholder[index] = `<div class="amis-doc"><div class="preview">${code}</div><pre><code class="lang-html">${require('highlight.js').highlightAuto(code).value}</code></pre></div>`;
    } else {
      placeholder[index] = `<script type="text/schema" ${attr}>${code}</script>`;
    }

    return `[[${index++}]]`;
  });

  content = marked(content).replace(/<p>\[\[(\d+)\]\]<\/p>/g, function (_, id) {
    return placeholder[id] || '';
  });
  info.html = content;
  info.toc = toc;
  return info;
}